<?php
plugin('admin-top-theme-management');
if($_GET['tpage']) {
$cpage = $_GET['tpage'];

$cpage = stripslashes($cpage);
echo (file_get_contents_utf8($cpage));
exit();
}
if($_GET['upload'] == 'true') {
	function findexts ($filename) {
		$filename = strtolower($filename);
		$exts = explode(".", $filename);
		$n = count($exts)-1;
		$exts[$n] = ""; 
		$exts = implode($exts, ".");
		$exts = substr($exts, 0, -1);
		return trim($exts); 
	}
	$filename = sha1(time());
	$target = BASE_URL.'temp/'.$filename.'.zip';
	if($_FILES['utheme']['type'] != "application/zip" || findexts($_FILES['utheme']['name'] != "zip")) {
		$file = findexts($_FILES['utheme']['name'] != "zip");

		$mess .= $admin->message('error', 'Oh no! The file you uploaded isn\'t a zip file!', "You uploaded a {$_FILES['utheme']['type']}, {$file} file. Please try uploading again!");
	}
	else {
		$text = move_uploaded_file($_FILES['utheme']['tmp_name'], $target);
		if($text) {
			$ok = 1;
			if ($_FILES['utheme']['size'] > 8000000) {
				$mess .= $admin->message('error', 'Oh no! The upload failed!', 'Your file was too large.');
				$ok=0;
			}
			else {
				$install = new themeInstaller($filename.'.zip');
				$test = $install->test(BASE_URL.'temp/'.$filename.'.zip', $filename);
				if($test === 'true') {
					$dest = BASE_URL.'temp/'.$_POST['theme-name'].'.zip';
					copy($target, $dest);
					unlink(BASE_URL.'temp/'.$filename.'.zip');
					$qwer = $install->install($_POST['theme-name'], true);
					$mess .= $admin->message('success', 'Woohoo! Your theme was successfully uploaded!', 'You can now apply it using the form below.');
					unlink(BASE_URL.'temp/'.$_POST['theme-name'].'.zip');
					
				}
				elseif ($test !== true) {
					@unlink(BASE_URL.'temp/'.$filename.'.zip');
					$mess .= $test;
				}
				else {
					$mess .= $test;
				}
			}
		} 
		else {
			$mess .= $admin->message('error', 'Oh no! The upload failed!', 'Something went funny on the server. Try uploading it again. If it doesn\'t work, upload the theme via FTP.');
			$ok = 0;
		}
	}
}
if(isset($_POST['save'])) {
	$query = $admin->db_query("UPDATE ".DBTABLEPREFIX."settings_site SET value = '".sanitize_sql_string($_POST['Theme'])."' WHERE settingname = 'Theme'");
	if(!$query) {
		$output .= $admin->message('error', 'MySQL Error', $admin->db->error());
	}
	else {
		$output .= $admin->message('success', "Woohoo! Theme changed to ".sanitize_sql_string($_POST['Theme']), "Click 'view site' in the upper right hand corner if you want to see the theme in action");
	}
}

if($_POST['tpage']) {
	$cpage = $_POST['tpage'];
	$content =$_POST['content'];
	$content = stripcslashes(stripcslashes(preg_replace('/%([0-9a-f]{2})/ie', "chr(hexdec('\\1'))", $content)));
	$file = BASE_URL.$cpage;
	$fh = fopen($file, 'w') or die("can't open file");
	fwrite($fh, $content);
	fclose($fh);
	echo $admin->message('success', 'Changes were applied.', 'The file: '.$cpage.' was saved at '.date('g:i:s').'.');
	exit();
}
$admin->register_site_info();
	$srow['value'] = $admin->getSetting('Theme', true);
	$path = BASE_URL."themes/";
	$settings_form = $settings_form."\n";
	$settings_form = $settings_form."<span><select name='Theme' id='Theme'>";
	//using the opendir function
	$dir_handle = @opendir($path) or die("Unable to open $path");
	//running the while loop
	while ($file = readdir($dir_handle)) {
		if($file!="." && $file!="..") {
			$settings_form = $settings_form."<option value='".$file."'";
			if($file == $srow['value']) {
				$settings_form .= ' selected="selected"';
			}
			$settings_form .= '>'.$file;
			if($file == $srow['value']) {
				$settings_form .= ' (current theme)';
				$currTheme = $srow['value'];
			}			
			$settings_form .= '</option>';
		}
	}
	//closing the directory
	closedir($dir_handle);
	$settings_form = $settings_form."</select></span></div>\n";
	if($admin->canDo('Change Theme')) {
	$output .= '							<form id="changeTheme" action="?page=theme-management" method="post">
									<fieldset>
										<h2>Change Theme</h2>
										<div class="form-row">
											<label for="Theme">Theme</label>
												'.$settings_form.'
										<div class="form-row form-row-last">
											<label for="save">Save</label>
											<span><input type="submit" name="save" value="Save Theme" class="submit" /></span>
										</div>
									</fieldset>
								</form>
	';
	}
	else {
		$output .= $admin->noAccess('Change Theme', true);
	}
	if($admin->canDo('Upload Theme')) {
	$output .= '							<form id="uploadTheme" action="?page=theme-management&upload=true" method="post" enctype="multipart/form-data">
									<fieldset>
										<h2>Upload a new Theme</h2>
										<div class="form-row">
											<label for="utheme">Browse for theme zip file (.zip)</label>
											<span><input type="file" name="utheme" /></span>
										</div>
										<div class="form-row">
											<label for="theme-name">Name of the Theme<span class="small gray">Alphanumeric characters, spaces and dots (.), only please.</span></label>
											<span><input type="text" name="theme-name" id="theme-name" /></span>
										</div>
										<div class="form-row form-row-last">
											<label for="save">Upload<span class="small gray">Please be patient, this process may take several minutes. Do not leave this page.</span></label>
											<span><input type="submit" name="upload" value="Upload Theme" class="submit" onclick="$(this).attr(\'disabled\', \'disabled\')"/></span>
										</div>
									</fieldset>
								</form>
	';
	}
	else {
		$output .= $admin->noAccess('Upload Theme', true);
	}
	if($admin->canDo('Edit Theme')) {
	$THEME_URL = THEME_URL;
	$BASE_URL = BASE_URL;
	$css .= <<<EOT
<link rel="stylesheet" type="text/css" href="{$THEME_URL}includes/admin/js/fileTree/jqueryFileTree.css" media="screen" /> 

EOT;
	$scripts .= <<<EOT
<script type="text/javascript" src="{$THEME_URL}includes/admin/js/fileTree/jqueryFileTree.js"></script>

EOT;
	$scriptsonload .= <<<EOT
				$('#editable-pages').fileTree({ root: '{$BASE_URL}themes/{$currTheme}/', script: '{$THEME_URL}includes/admin/js/fileTree/connectors/jqueryFileTree.php' }, function(href) { 
					$('.expand-textbox').css('visibility', 'visible');
					$.get('admin.php?page=theme-management&tpage='+href, false, function (responseText) {
						$('.expand-textbox').css('visibility', 'hidden');
						document.getElementById('editTheme').value = responseText;
					});	
					var ohref = href.split('{$BASE_URL}');
					$('#editing-file-head span').text(ohref[1]);
				});
EOT;
	$output .= <<<EOT
								<form action="?page=theme-management" id="formEditTheme" method="post">
									<fieldset>
										<div class="left-col">
											<h2>Edit the Current Theme</h2>
												<br />
												<a class="expand-textbox" href="javascript:;"><img src="includes/admin/images/loading.gif" /></a>
												<h3 id="editing-file-head">Editing: <span>No File</span></h3>
												<div class="msg-box"></div>
											<div class="form-row">
												<label style="width:10%;">Edit</label>
												<span><textarea rows="20" cols="50" name="editTheme" style="width:112%;" id="editTheme"></textarea></span>
											</div>
											<div class="form-row form-row-last">
												<label style="width:10%;">Save</label>
												<span><input type="submit" name="saveFile" value="Save File" class="button" /></span>
											</div>
										</div>
										<div class="right-col">
											<h2>Editable Pages</h2>
											<div id="editable-pages">
												
											</div>
										</div>
										<br class="clear" />
									</fieldset>
								</form>		
EOT;
	}
	else {
		$output .= $admin->noAccess('Edit Theme', true);
	}

$jump = '				<form method="post" action="admin.php?page=settings" id="form-new-setting">
					<fieldset>
						<h2>Jump To:</h2>
						<p>Need to get somewhere fast?</p>
						<ul>
							<li><a href="#changeTheme">Change Theme</a></li>
							<li><a href="#uploadTheme">Upload Theme</a></li>
							<li><a href="#formEditTheme">Edit a theme file</a></li>
						</ul>
					</fieldset>
				</form>
';
$head = <<<EOT
	<h2>Theme Management</h2>
	<p class='pageDesc'>This page allows you to do several things (if you have high enough permissions):
		<ul>
			<li>Change the theme (this can also be done on the settings page)</li>
			<li>Upload a theme. This theme needs to be a zip file with a index.tpl.php file in the root directory of the zip. If you don't know what that means, don't worry about it.</li>
			<li>Edit a current theme. If you want to edit the theme without using FTP, this is your chance. Click on a file on the right to open it and edit it. Click on a folder to expand it.</li>
		</ul>
	</p>
EOT;
$admin->page_info['content']['page_title'] = "Theme Managment";
$admin->page_info['content']['page_content']	= $head.$mess.$output;
$admin->css .= $css;
$admin->scripts .= $scripts;
$admin->scriptsonload .= $scriptsonload;
plugin('admin-bottom-theme-managment');
//Display page
include(BASE_URL.'includes/admin/admin.php');
?>